<template>
	<view class="buygift-card" v-if="!isExpired">
		<view class="card-header">
			<view class="header-content">
				<view class="header-top">
					<text class="activity-name">{{ promotion.promName }}</text>
					<cl-tag :type="statusType" size="small">{{ statusText }}</cl-tag>
				</view>
				<view class="header-bottom">
					<view class="time-info">
						<cl-icon name="time" size="14" color="#fff"></cl-icon>
						<text class="time-text">{{ formatActivityTime() }}</text>
					</view>
					<text class="remaining-time" v-if="!isExpired">{{
						promotion.remainingTime || "进行中"
					}}</text>
				</view>
			</view>
		</view>

		<view class="content">
			<!-- 买赠规则列表 -->
			<view v-for="(rule, index) in promotion.details" :key="index" class="rule-section">
				<!-- 主商品 -->
				<view class="main-goods">
					<view class="section-label">
						<cl-icon name="shopping-cart" size="18" color="#2979ff"></cl-icon>
						<text class="label-text">购买商品</text>
					</view>
					<view class="goods-card" v-if="rule.goodsInfo">
						<cl-image
							:src="'https://shop.sdamdyy.cn/' + (rule.goodsInfo.mainPic || '')"
							:alt="rule.goodsInfo.title"
							class="goods-image"
							width="160rpx"
							height="160rpx"
							mode="aspectFill"
							:lazy-load="true"
							fallback="/static/empty/no.jpg"
						/>
						<view class="goods-info">
							<text class="goods-name">{{ rule.goodsInfo.title }}</text>
							<text class="goods-spec"
								>{{ rule.goodsInfo.goodsSpec }} {{ rule.goodsInfo.unit }}</text
							>
							<text class="goods-manufacturer">{{
								rule.goodsInfo.manufacturer
							}}</text>
							<!-- 近效期日期 -->
							<view class="expiry-info" v-if="rule.goodsInfo.nearestExpiredDate">
								<cl-icon name="time" size="12" color="#ff9800"></cl-icon>
								<text class="expiry-text"
									>效期至:
									{{ formatExpiryDate(rule.goodsInfo.nearestExpiredDate) }}</text
								>
							</view>
							<view class="price-row">
								<view class="price-display" v-if="userStore.token">
									<text class="goods-price">{{
										formatUserPrice(
											rule.goodsInfo.price,
											userStore,
											rule.goodsInfo.noDiscounts
										)
									}}</text>
									<text class="original-price">
										{{ formatUserPrice(rule.goodsInfo.price, userStore, 1) }}
									</text>
								</view>
								<text v-else class="login-tip">登录查看价格</text>
								<view class="buy-condition">
									<text class="condition-text"
										>买{{ Number(rule.num || 1)
										}}{{ rule.goodsInfo.unit }}</text
									>
								</view>
							</view>
						</view>
					</view>
				</view>

				<!-- 赠品列表 -->
				<view class="gift-section" v-if="rule.freeGoodsInfo">
					<view class="section-label">
						<cl-icon name="gift" size="18" color="#ff6b6b"></cl-icon>
						<text class="label-text">赠送商品</text>
					</view>
					<view class="gift-list">
						<view class="gift-item">
							<cl-image
								:src="
									'https://shop.sdamdyy.cn/' + (rule.freeGoodsInfo.mainPic || '')
								"
								:alt="rule.freeGoodsInfo.title"
								class="gift-image"
								width="80rpx"
								height="80rpx"
								mode="aspectFill"
								:lazy-load="true"
								fallback="/static/empty/no.jpg"
							/>
							<view class="gift-info">
								<text class="gift-name">{{
									rule.freeGoodsInfo.title || "赠品"
								}}</text>
								<text class="gift-spec"
									>{{ rule.freeGoodsInfo.goodsSpec || "" }}
									{{ rule.freeGoodsInfo.unit || "" }}</text
								>
								<text class="gift-manufacturer">{{
									rule.freeGoodsInfo.manufacturer || ""
								}}</text>
								<!-- 赠品近效期日期 -->
								<view
									class="gift-expiry-info"
									v-if="rule.freeGoodsInfo.nearestExpiredDate"
								>
									<cl-icon name="time" size="10" color="#ff9800"></cl-icon>
									<text class="gift-expiry-text"
										>效期至:
										{{
											formatExpiryDate(rule.freeGoodsInfo.nearestExpiredDate)
										}}</text
									>
								</view>
								<view class="gift-value">
									<text class="value-label">价值:</text>
									<text class="value-price"
										>¥{{ Number(rule.freeTaxPrice || 0).toFixed(2) }}</text
									>
									<text class="gift-quantity"
										>x{{ Number(rule.freeNum || 1) }}</text
									>
								</view>
							</view>
							<view class="gift-tag">
								<text class="tag-text">赠品</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 购买操作 -->
				<view class="action-area">
					<view class="quantity-selector">
						<text class="quantity-label">购买数量：</text>
						<cl-input-number
							v-model="quantities[index]"
							:min="Number(rule.num || 1)"
							:step="Number(rule.num || 1)"
							:max="99"
							:size="30"
						/>
						<text class="quantity-tips">{{ Number(rule.num || 1) }}的倍数</text>
					</view>
					<cl-button type="primary" size="small" round @tap="handleBuy(rule, index)">
						立即购买
					</cl-button>
				</view>
			</view>
		</view>

		<!-- 活动信息 -->
		<view class="footer-info">
			<view class="info-item">
				<cl-icon name="time" size="14" color="#999"></cl-icon>
				<text class="info-text">{{ formatActivityTime() }}</text>
			</view>
			<view class="info-item">
				<cl-icon name="tag" size="14" color="#999"></cl-icon>
				<text class="info-text">数量有限，赠完即止</text>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { ref, watch, computed } from "vue";
import { useCool } from "/@/cool";
import { useStore } from "/@/cool/store";
import { formatUserPrice, getPriceDisplay } from "/@/utils/price";
import dayjs from "dayjs";

const { service, router } = useCool();
const { user: userStore } = useStore();

const props = defineProps<{
	promotion: any;
}>();

const emit = defineEmits(["join"]);

// 每个规则的购买数量
const quantities = ref<number[]>([]);

// 计算活动是否过期
const isExpired = computed(() => {
	const now = dayjs();
	const end = dayjs(props.promotion.endTime);
	return now.isAfter(end);
});

// 计算活动状态类型
const statusType = computed(() => {
	const now = dayjs();
	const start = dayjs(props.promotion.startTime);
	const end = dayjs(props.promotion.endTime);

	if (now.isBefore(start)) return "warning";
	if (now.isAfter(end)) return "info";
	return "success";
});

// 计算活动状态文本
const statusText = computed(() => {
	const now = dayjs();
	const start = dayjs(props.promotion.startTime);
	const end = dayjs(props.promotion.endTime);

	if (now.isBefore(start)) return "未开始";
	if (now.isAfter(end)) return "已结束";
	return "进行中";
});

// 初始化数量数组
watch(
	() => props.promotion.details,
	(details) => {
		if (details && details.length > 0) {
			quantities.value = details.map((rule: any) => Number(rule.num || 1));
		}
	},
	{ immediate: true }
);

// 处理购买
async function handleBuy(rule: any, index: number) {
	try {
		uni.showLoading({ title: "下单中..." });

		// 调用买赠下单接口
		await service.goods.promo.createBuyGiftOrder({
			billNo: props.promotion.billNo,
			goodsId: rule.goodsId,
			quantity: quantities.value[index],
		});

		uni.hideLoading();
		uni.showToast({
			title: "下单成功",
			icon: "success",
		});

		// 跳转到订单页面
		setTimeout(() => {
			router.push("/pages/order/list");
		}, 1500);
	} catch (error: any) {
		uni.hideLoading();
		uni.showToast({
			title: error.message || "下单失败",
			icon: "none",
		});
	}
}

// 格式化活动时间
function formatActivityTime(): string {
	const start = dayjs(props.promotion.startTime);
	const end = dayjs(props.promotion.endTime);
	return `${start.format("MM/DD HH:mm")} - ${end.format("MM/DD HH:mm")}`;
}

// 格式化效期日期
function formatExpiryDate(date: string): string {
	if (!date) return "";
	return dayjs(date).format("YYYY-MM-DD");
}
</script>

<style lang="scss" scoped>
.buygift-card {
	background: #fff;
	border-radius: 16rpx;
	overflow: hidden;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

	.card-header {
		position: relative;
		padding: 32rpx;
		background: linear-gradient(135deg, #2979ff 0%, #5c6bc0 100%);
		color: #fff;
		overflow: hidden;

		&::before {
			content: "";
			position: absolute;
			top: -50%;
			right: -20%;
			width: 300rpx;
			height: 300rpx;
			background: rgba(255, 255, 255, 0.1);
			border-radius: 50%;
		}

		&::after {
			content: "";
			position: absolute;
			bottom: -30%;
			left: -10%;
			width: 200rpx;
			height: 200rpx;
			background: rgba(255, 255, 255, 0.08);
			border-radius: 50%;
		}

		.header-content {
			position: relative;
			z-index: 1;

			.header-top {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 16rpx;

				.activity-name {
					font-size: 36rpx;
					font-weight: bold;
					flex: 1;
					margin-right: 16rpx;
				}
			}

			.header-bottom {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.time-info {
					display: flex;
					align-items: center;
					gap: 8rpx;

					.time-text {
						font-size: 24rpx;
						opacity: 0.9;
					}
				}

				.remaining-time {
					font-size: 24rpx;
					opacity: 0.9;
				}
			}
		}
	}

	.content {
		padding: 24rpx;

		.rule-section {
			border: 1px solid #e8eaf6;
			border-radius: 12rpx;
			padding: 20rpx;
			margin-bottom: 20rpx;

			&:last-child {
				margin-bottom: 0;
			}

			.section-label {
				display: flex;
				align-items: center;
				gap: 8rpx;
				margin-bottom: 16rpx;

				.label-text {
					font-size: 28rpx;
					font-weight: 500;
					color: #333;
				}
			}

			.main-goods {
				margin-bottom: 24rpx;

				.goods-card {
					display: flex;
					gap: 16rpx;
					background: #f5f5f5;
					padding: 16rpx;
					border-radius: 8rpx;

					.goods-image {
						width: 160rpx;
						height: 160rpx;
						border-radius: 8rpx;
						flex-shrink: 0;
					}

					.goods-info {
						flex: 1;
						display: flex;
						flex-direction: column;
						gap: 8rpx;

						.goods-name {
							font-size: 30rpx;
							font-weight: 500;
							color: #333;
							display: -webkit-box;
							-webkit-box-orient: vertical;
							-webkit-line-clamp: 2;
							line-clamp: 2;
							overflow: hidden;
						}

						.goods-spec {
							font-size: 24rpx;
							color: #666;
						}

						.goods-manufacturer {
							font-size: 24rpx;
							color: #999;
						}

						.expiry-info {
							display: flex;
							align-items: center;
							gap: 8rpx;
							margin-top: 8rpx;
							padding: 8rpx 16rpx;
							background: rgba(255, 152, 0, 0.1);
							border-radius: 20rpx;
							width: fit-content;

							.expiry-text {
								font-size: 22rpx;
								color: #ff9800;
								font-weight: 500;
							}
						}

						.price-row {
							display: flex;
							justify-content: space-between;
							align-items: center;
							margin-top: auto;

							.price-display {
								display: flex;
								align-items: baseline;
								gap: 8rpx;
							}

							.goods-price {
								font-size: 32rpx;
								font-weight: bold;
								color: #ff6b6b;
							}

							.original-price {
								font-size: 26rpx;
								color: #999;
								text-decoration: line-through;
							}

							.login-tip {
								font-size: 28rpx;
								color: #ff6b6b;
							}

							.buy-condition {
								background: #2979ff;
								color: #fff;
								padding: 6rpx 16rpx;
								border-radius: 20rpx;

								.condition-text {
									font-size: 24rpx;
								}
							}
						}
					}
				}
			}

			.gift-section {
				margin-bottom: 24rpx;

				.gift-list {
					display: flex;
					flex-direction: column;
					gap: 12rpx;

					.gift-item {
						display: flex;
						align-items: center;
						gap: 12rpx;
						background: #fff5f5;
						padding: 12rpx;
						border-radius: 8rpx;
						border: 1px dashed #ffcdd2;
						position: relative;

						.gift-image {
							width: 80rpx;
							height: 80rpx;
							border-radius: 6rpx;
							flex-shrink: 0;
						}

						.gift-info {
							flex: 1;
							display: flex;
							flex-direction: column;
							gap: 6rpx;

							.gift-name {
								font-size: 26rpx;
								color: #333;
								display: -webkit-box;
								-webkit-box-orient: vertical;
								-webkit-line-clamp: 1;
								line-clamp: 1;
								overflow: hidden;
							}

							.gift-spec {
								font-size: 22rpx;
								color: #999;
							}

							.gift-manufacturer {
								font-size: 22rpx;
								color: #999;
							}

							.gift-expiry-info {
								display: flex;
								align-items: center;
								gap: 6rpx;
								margin-top: 6rpx;
								padding: 6rpx 12rpx;
								background: rgba(255, 152, 0, 0.1);
								border-radius: 16rpx;
								width: fit-content;

								.gift-expiry-text {
									font-size: 20rpx;
									color: #ff9800;
									font-weight: 500;
								}
							}

							.gift-value {
								display: flex;
								align-items: center;
								gap: 8rpx;
								font-size: 24rpx;

								.value-label {
									color: #999;
								}

								.value-price {
									color: #ff6b6b;
									font-weight: 500;
								}

								.gift-quantity {
									color: #666;
								}
							}
						}

						.gift-tag {
							position: absolute;
							top: 0;
							right: 0;
							background: #ff6b6b;
							color: #fff;
							padding: 4rpx 12rpx;
							border-radius: 0 8rpx 0 16rpx;

							.tag-text {
								font-size: 20rpx;
							}
						}
					}
				}
			}

			.action-area {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.quantity-selector {
					display: flex;
					align-items: center;
					gap: 12rpx;

					.quantity-label {
						font-size: 26rpx;
						color: #666;
					}

					.quantity-tips {
						font-size: 22rpx;
						color: #999;
						margin-left: 8rpx;
					}
				}
			}
		}
	}

	.footer-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 16rpx 24rpx;
		background: #f8f8f8;

		.info-item {
			display: flex;
			align-items: center;
			gap: 8rpx;

			.info-text {
				font-size: 24rpx;
				color: #999;
			}
		}
	}
}
</style>
